/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.chl.mq._04_routing;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.util.Random;
import java.util.UUID;

/**
 *
 * @author 陈宏亮
 */
public class EmitLogDirect {

    private static final String EXCHANGE_NAME = "ex_logs_direct";
    private static final String[] SEVERITIES = {"info", "warning", "error"};

    public static void main(String[] argv) throws Exception {
        // 创建连接和频道  
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.2.221");
        factory.setUsername("guest");
        factory.setPassword("guest");
        try (Connection connection = factory.newConnection()) {
            Channel channel = connection.createChannel();
            // 声明转发器的类型  
            channel.exchangeDeclare(EXCHANGE_NAME, "direct");

            //发送6条消息  
            for (int i = 0; i < 10; i++) {
                String severity = getSeverity();
                String message = severity + "日志 :" + UUID.randomUUID().toString();
                // 发布消息至转发器，指定routingkey  
                channel.basicPublish(EXCHANGE_NAME, severity, null, message
                        .getBytes());
                System.out.println(" 发送 '" + message + "'");
            }

            channel.close();
        }
    }

    /**
     * 随机产生一种日志类型
     *
     * @return
     */
    private static String getSeverity() {
        Random random = new Random();
        int ranVal = random.nextInt(3);
        return SEVERITIES[ranVal];
    }
}
